package org.kepler.chat.api.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.bigdata.frame.common.BaseLogger;
import org.bigdata.frame.exception.BizException;
import org.kepler.chat.api.entity.User;
import org.kepler.chat.api.infra.security.auth.jwt.extractor.TokenExtractor;
import org.kepler.chat.api.infra.security.config.JwtSettings;
import org.kepler.chat.api.infra.security.config.WebSecurityConfig;
import org.kepler.chat.api.infra.security.model.token.RawAccessJwtToken;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.kepler.loan.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author liuke
 * @date 2018/10/2 21:54
 */
public class BaseApi extends BaseLogger {
    @Autowired
    private JwtSettings jwtSettings;
    @Autowired
    @Qualifier("jwtHeaderTokenExtractor")
    private TokenExtractor tokenExtractor;
    @Resource
    protected IUserService userService;

    public User getLoginUser(HttpServletRequest request) {
        String tokenPayload = tokenExtractor.extract(request.getHeader(WebSecurityConfig.AUTHENTICATION_HEADER_NAME));
        RawAccessJwtToken rawToken = new RawAccessJwtToken(tokenPayload);
        Jws<Claims> claims = rawToken.parseClaims(jwtSettings.getTokenSigningKey());
        String subject = claims.getBody().getSubject();
        User userByAccount = userService.findUserByAccount(subject);
        if (null == userByAccount) {
            throw new BizException(ErrorCode.USER_NOT_EXIST.getCode(), ErrorCode.USER_NOT_EXIST.getMessage());
        }
        return userByAccount;
    }
}
